import { type ActionType, FooterToolbar, PageContainer, type ProColumns, ProDescriptions, type ProDescriptionsItemProps, ProTable, } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Drawer, message, Space } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import { getCustomer } from '@/apis/customer';
import type { CustomerInfo } from '@/pages/customer/index.data';
import { removeRule } from '@/services/ant-design-pro/api';
import CreateForm, { type CreateFormRef, } from './components/CreateForm/CreateForm';
import { DriverInfo } from './index.data';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType | null>(null);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<any>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();

  const {run: delRun, loading} = useRequest(removeRule, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();

      messageApi.success('删除成功');
    },
    onError: () => {
      messageApi.error('删除失败，请重试');
    },
  });

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = useCallback(
    async ( selectedRows: API.RuleListItem[] ) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');

        return;
      }
    },
    [delRun, messageApi.warning],
  );

  const handleDelete = useCallback(async ( record: any ) => {
    const res = await delRun(record.id);
  }, []);

  const createRef = useRef<CreateFormRef>(null);
  const handleEdit = ( record: CustomerInfo ) => {
    if (createRef.current) {
      createRef.current.handleEdit(record.id);
    }
  };

  /**
   * 列定义
   */
  const columns: ProColumns<DriverInfo>[] = [
    {
      title: '司机ID',
      dataIndex: 'driver_id',
      key: 'driver_id',
      width: 80,
      search: false,
      fixed: 'left',
    },
    {
      title: '司机姓名',
      dataIndex: 'driver_name',
      key: 'driver_name',
      width: 120,
      fixed: 'left',
    },
    {
      title: '速记码',
      dataIndex: 'shorthand_code',
      key: 'shorthand_code',
      width: 100,
      search: false,
    },
    {
      title: '手机号码',
      dataIndex: 'mobile_phone',
      key: 'mobile_phone',
      width: 120,
    },
    {
      title: '当前状态',
      dataIndex: 'current_status',
      key: 'current_status',
      width: 100,
      valueEnum: {
        激活: {text: '激活', status: 'Success'},
        停用: {text: '停用', status: 'Default'},
      },
    },
    {
      title: '身份证号',
      dataIndex: 'id_number',
      key: 'id_number',
      width: 160,
      search: false,
    },
    {
      title: '驾驶证号',
      dataIndex: 'driving_license_number',
      key: 'driving_license_number',
      width: 150,
      search: false,
    },
    {
      title: '出生日期',
      dataIndex: 'birth_date',
      key: 'birth_date',
      width: 110,
      valueType: 'date',
      search: false,
    },
    {
      title: '基本工资',
      dataIndex: 'base_salary',
      key: 'base_salary',
      width: 110,
      valueType: 'money',
      search: false,
    },
    {
      title: '是否有社保',
      dataIndex: 'has_social_insurance',
      key: 'has_social_insurance',
      width: 100,
      valueEnum: {
        1: {text: '是', status: 'Success'},
        0: {text: '否', status: 'Default'},
      },
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_time',
      key: 'created_time',
      width: 160,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updated_time',
      key: 'updated_time',
      width: 160,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: ( _, record ) => (
        <Space>
          <a
            key="edit"
            onClick={() => {
              createRef.current?.handleEdit(record.id);
            }}
          >
            编辑
          </a>
          <a
            key="delete"
            onClick={() => {
              handleDelete(record.driver_id);
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];


  return (
    <PageContainer>
      {contextHolder}
      <ProTable<DriverInfo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        tableLayout={'auto'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() =>
          [
            <CreateForm
              key="create"
              ref={createRef}
              reload={actionRef.current?.reload}
            />,
          ]
        }
        request={getCustomer}
        columns={columns}
        rowSelection={{
          onChange: ( _, selectedRows ) => {
            setSelectedRows(selectedRows);
          },
        }}
        scroll={{x: 2000, y: 400}}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage
                id="pages.searchTable.chosen"
                defaultMessage="Chosen"
              />{' '}
              <a style={{fontWeight: 600}}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage
                id="pages.searchTable.item"
                defaultMessage="项"
              />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce(
                  ( pre: any, item: { callNo: any } ) => pre + (item.callNo ?? 0),
                  0,
                )}{' '}
                <FormattedMessage
                  id="pages.searchTable.tenThousand"
                  defaultMessage="万"
                />
              </span>
            </div>
          }
        >
          <Button
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
